package io.renren.modules.grant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.grant.dao.NoticeTypeDao;
import io.renren.modules.grant.dto.NoticeTypeDTO;
import io.renren.modules.grant.entity.NoticeTypeEntity;
import io.renren.modules.grant.service.NoticeTypeService;
import io.renren.modules.grant.vo.NoticeTypeVO;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

/**
 * 公告类型
 */
@Service
public class NoticeTypeServiceImpl extends CrudServiceImpl<NoticeTypeDao, NoticeTypeEntity, NoticeTypeVO> implements NoticeTypeService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public QueryWrapper<NoticeTypeEntity> getWrapper(Map<String, Object> params) {
        String id = (String)params.get("id");
        String typeName = (String)params.get("typeName");

        QueryWrapper<NoticeTypeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.like(StringUtils.isNotBlank(typeName), "type_name", typeName);

        return wrapper;
    }

    @Override
    public void save(NoticeTypeDTO dto) {
        NoticeTypeEntity noticeTypeEntity = ConvertUtils.sourceToTarget(dto, NoticeTypeEntity.class);
        this.insert(noticeTypeEntity);
    }

    @Override
    public void update(NoticeTypeDTO dto) {
        NoticeTypeEntity noticeTypeEntity = ConvertUtils.sourceToTarget(dto, NoticeTypeEntity.class);
        this.updateById(noticeTypeEntity);
    }

    @Override
    public PageData<NoticeTypeVO> noticeTypePage(Map<String, Object> params) {
        List<SysUserDTO> userDtoList = sysUserService.getAll();
        PageData<NoticeTypeVO> page = this.page(params);
        page.getList().forEach(e -> {
            SysUserDTO creator = userDtoList.stream().filter(j -> j.getId().compareTo(e.getCreator()) == 0).findAny().orElse(null);
            e.setCreatorName(creator == null ? "-" : creator.getRealName());
            SysUserDTO updater = userDtoList.stream().filter(j -> j.getId().compareTo(e.getUpdater()) == 0).findAny().orElse(null);
            e.setUpdaterName(updater == null ? "-" : updater.getRealName());
        });
        return page;
    }

    @Override
    public List<NoticeTypeVO> getAll() {
        List<NoticeTypeEntity> entityList = this.baseDao.selectList(null);
        return ConvertUtils.sourceToTarget(entityList, NoticeTypeVO.class);
    }

}
